package com.snailvr.tv.ui.view;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.snail.readyvr.R;
import com.snail.readyvr.util.EventBus;
import com.snail.readyvr.util.StringUtils;
import com.snailvr.tv.event.MessageEvent;
import com.snailvr.tv.ui.adapter.EmojiGridAdapter;
import com.snailvr.tv.ui.adapter.GiftGridAdapter;
import com.snailvr.tv.ui.adapter.PhraseViewAdapter;
import com.snailvr.tv.ui.data.DefEmoticons;
import com.snailvr.tv.ui.data.DefGifticons;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;


/**
 * Created by Administrator on 2017/1/5.
 */

public class EmotionKeyboard extends RelativeLayout {
    private int EMOJI_NUM = 12 * 3 - 1;  // GridView 12 列 3 行 + 1 delete

    private int GIFT_NUM = 7 * 2;
    private boolean mIsToAnchor = false;

    private Context mContext;
    protected LayoutInflater mInflater;

    private GridView mGridViewEmoji;
    private EmojiGridAdapter mEmojiGridAdapter;
    private PhraseViewAdapter mPhraseViewAdapter;
    private int mEmojiPageNum;

    private GridView mGridViewGift;
    private GiftGridAdapter mGiftGridAdapter;
    private int mGiftPageNum;

    private List<View> mEmojiViews = new ArrayList<>();
    private List<View> mGiftViews = new ArrayList<>();
    private List<String> mStringList = new ArrayList<String>();

    private InputMethodManager mInputMethodManager;

    @BindView(R.id.view_pager_emoji)
    ViewPager mViewPagerEmoji;

    @BindView(R.id.indicator_emoji)
    CirclePageIndicator mCirclePageIndicatorEmoji;

    @BindView(R.id.view_pager_gift)
    ViewPager mViewPagerGift;

    @BindView(R.id.indicator_gift)
    CirclePageIndicator mCirclePageIndicatorGift;

    @BindView(R.id.edit_text_keyboard)
    EditText mEditText;

    @BindView(R.id.img_view_keyboard)
    ImageView mImgKeyBorad;

    @BindView(R.id.img_view_phrase)
    ImageView mImgPhrase;

    @BindView(R.id.img_view_emoji)
    ImageView mImgEmoji;

    @BindView(R.id.img_view_gift)
    ImageView mImgGift;

    @BindView(R.id.Layout_phrase)
    RelativeLayout mLayout_phrase;

    @BindView(R.id.Layout_emoji)
    RelativeLayout mLayout_emoji;

    @BindView(R.id.Layout_gift)
    RelativeLayout mLayout_gift;

    @BindView(R.id.button_send_message)
    Button mButtonSend;

    @BindView(R.id.id_list_view_phrase)
    ListView mListViewPhrase;

    @BindView(R.id.send_spinner)
    Spinner mSendSelectSpinner;

    @OnClick(R.id.button_send_message)
    void sendMessage() {
        if (!StringUtils.isEmpty(mEditText.getText().toString())) {
            String _message = mEditText.getText().toString();

            EventBus.getDefault().post(new MessageEvent(_message,mIsToAnchor));
            mEditText.setText("");
        }
    }

    @OnClick(R.id.img_view_keyboard)
    void showInputMethod() {
        hideAllLayouts();
        mInputMethodManager.showSoftInput(mEditText, 0);
    }

    @OnClick(R.id.img_view_phrase)
    void showPhraseView() {
        mInputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
        mLayout_emoji.setVisibility(GONE);
        mLayout_gift.setVisibility(GONE);
        mLayout_phrase.setVisibility(VISIBLE);
    }

    @OnClick(R.id.img_view_gift)
    void showGiftView() {
        mInputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
        mLayout_emoji.setVisibility(GONE);
        mLayout_phrase.setVisibility(GONE);
        mLayout_gift.setVisibility(VISIBLE);
    }

    @OnClick(R.id.img_view_emoji)
    void showEmojiView() {
        mInputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
        mLayout_gift.setVisibility(GONE);
        mLayout_phrase.setVisibility(GONE);
        mLayout_emoji.setVisibility(VISIBLE);

    }


    public EmotionKeyboard(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mInputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        String[] _Strings = mContext.getResources().getStringArray(R.array.phrase_list);
        mStringList = Arrays.asList(_Strings);
        Log.i("EmotionKeyboard", "string size:" + mStringList.size() + mStringList.get(1));

        initView();
        EventBus.getDefault().register(this);

    }


    private void initView() {

        View _view = mInflater.inflate(R.layout.emotionkeyborad, this);
        ButterKnife.bind(_view);

        /**
         * ------------
         * init phrase view
         * ------------
         */
        mPhraseViewAdapter = new PhraseViewAdapter(mContext, mStringList);
        mListViewPhrase.setAdapter(mPhraseViewAdapter);
        mListViewPhrase.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String _temp = mEditText.getText().toString();
                _temp = _temp + mStringList.get(position);
                mEditText.setText(_temp);
            }
        });


        /**
         * --------------
         *init emoji view
         * --------------
         */
        int emotion_size = DefEmoticons.emoticonHashMap.size();
        mEmojiPageNum = emotion_size / EMOJI_NUM;
        if (emotion_size % EMOJI_NUM > 0) {
            mEmojiPageNum++;
        }

        Iterator<String> iterator_emoji = DefEmoticons.emoticonHashMap.keySet().iterator();

        for (int p = 1; p <= mEmojiPageNum; p++) {

            final List<String> icon_str = new ArrayList<>();

            for (int i = 0; i < EMOJI_NUM; i++) {
                if (iterator_emoji.hasNext())
                    icon_str.add(iterator_emoji.next());
            }
            icon_str.add("[delete]");
            mGridViewEmoji = (GridView) mInflater.inflate(R.layout.emoji_grid_view, this, false);
            mEmojiGridAdapter = new EmojiGridAdapter(mContext, icon_str);
            mGridViewEmoji.setAdapter(mEmojiGridAdapter);

            mEmojiViews.add(mGridViewEmoji);
            mGridViewEmoji.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String _icon = icon_str.get(position);
                    String _temp = mEditText.getText().toString();

                    if (_icon.equals("[delete]")) {
                        if (_temp.endsWith("]")) {
                            int offset = _temp.lastIndexOf("[");
                            _temp = _temp.substring(0, offset);
                        } else if (_temp.length() > 0) {
                            _temp = _temp.substring(0, _temp.length() - 1);
                        }
                    } else {
                        _temp = _temp + _icon;
                        mEditText.setText(_temp);
                    }
                    mEditText.setText(_temp);
                }
            });
        }


        MyPagerAdapter emojiPagerAdapter = new MyPagerAdapter(mEmojiViews);
        mViewPagerEmoji.setAdapter(emojiPagerAdapter);

        mCirclePageIndicatorEmoji.setViewPager(mViewPagerEmoji);
        mCirclePageIndicatorEmoji.setSnap(false);

        /**
         * --------------
         *init gift view
         * --------------
         */
        int gift_size = DefGifticons.giftHashMap.size();
        mGiftPageNum = gift_size / GIFT_NUM;
        if (gift_size % GIFT_NUM > 0) {
            mGiftPageNum++;
        }
        Log.i(TAG, "gift_size:" + gift_size + "mGiftPageNum:" + mGiftPageNum);


        Iterator<String> iterator_gift = DefGifticons.giftHashMap.keySet().iterator();

        for (int p = 1; p <= mGiftPageNum; p++) {

            List<String> icon_str = new ArrayList<>();

            for (int i = 0; i < GIFT_NUM; i++) {
                if (iterator_gift.hasNext())
                    icon_str.add(iterator_gift.next());
            }
            mGridViewGift = (GridView) mInflater.inflate(R.layout.gift_grid_view, this, false);
            mGiftGridAdapter = new GiftGridAdapter(mContext, icon_str);
            mGridViewGift.setAdapter(mGiftGridAdapter);

            mGiftViews.add(mGridViewGift);

        }

        MyPagerAdapter giftPagerAdapter = new MyPagerAdapter(mGiftViews);
        mViewPagerGift.setAdapter(giftPagerAdapter);

        mCirclePageIndicatorGift.setViewPager(mViewPagerGift);
        mCirclePageIndicatorGift.setSnap(false);

        /**
         * ----------
         * Edit aciton
         * ----------
         */
        mEditText.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                boolean bool = mInputMethodManager.showSoftInput(v, 0);
                if (bool) {
                    mLayout_gift.setVisibility(GONE);
                    mLayout_emoji.setVisibility(GONE);
                }
                return false;
            }
        });
        mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String _message = v.getText().toString();
                EventBus.getDefault().post(new MessageEvent(_message,mIsToAnchor));
                mEditText.setText("");
                return false;
            }
        });


        /**
         * --------
         * Spinner
         * --------
          */
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(mContext,
                android.R.layout.simple_spinner_item,
                mContext.getResources().getStringArray(R.array.send_select));
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
        mSendSelectSpinner.setAdapter(arrayAdapter);

        mSendSelectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0) {
                    mIsToAnchor = false;
                } else if (position == 1) {
                    mIsToAnchor = true;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }


    void hideAllLayouts() {
        mLayout_phrase.setVisibility(GONE);
        mLayout_emoji.setVisibility(GONE);
        mLayout_gift.setVisibility(GONE);
    }

    //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));//删除页卡
        }

    }

    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = ((Activity) mContext).getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        ((Activity) mContext).getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

        return screenHeight - rect.bottom - getSoftButtonsBarHeight() != 0;
    }

    /**
     * 底部虚拟按键栏的高度
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private int getSoftButtonsBarHeight() {
        DisplayMetrics metrics = new DisplayMetrics();
        //这个方法获取可能不是真实屏幕的高度
        ((Activity) mContext).getWindow().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        //获取当前屏幕的真实高度
        ((Activity) mContext).getWindow().getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }

    }

    public void setEditeText(String text) {
        mEditText.setText(text);

    }


}
